﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Management;
using System.Windows.Forms;

namespace YJYpublicClass
{
    class PublicFuntions
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);
        /// <summary>
        /// 强制结束进程
        /// </summary>
        public static void KillProcess(string ProcessName)
        {
            Process[] cur = Process.GetProcesses();
            for (int i = 0; i < cur.Length; i++)
            {
                if (cur[i].ProcessName == ProcessName)
                {
                    cur[i].Kill();
                }
            }
        }

        /// <summary>
        /// 写入数据至INI文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        /// <param name="Path"></param>
        public static void WriteINI(string section, string key, string Value, string Path)
        {
            WritePrivateProfileString(section, key, Value, Path);
        }

        /// <summary>
        /// 从INI文件读取数据
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="Standard"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static string GetINI(string section, string key, string Standard, string Path)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, Standard, temp, 255, Path);

            return temp.ToString();
        }

        /// <summary>
        /// 查询文件路径是否存在，不存在则根据路径创建文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="IsCreateFile"></param>
        public static void CreateFile(string FilePath)
        {
            try
            {
                if (System.IO.File.Exists(FilePath) == false)
                {
                    System.IO.Directory.CreateDirectory(FilePath);
                }
            }
            catch (Exception ex)
            {
                SaveErrorLog(外设.SysPras.Logpath, "CreateFile::" + ex.ToString());
            }
        }

        /// <summary>
        /// 打开任意类型文档
        /// </summary>
        /// <param name="Path"></param>
        public static Boolean OpenDocument(string Path)
        {
            try
            {
                if (System.IO.File.Exists(Path))
                {
                    System.Diagnostics.Process.Start(Path);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 获取当前软件的内存占用
        /// </summary>
        public static string GetSoftWareARM()
        {
            try
            {
                Process CurrentProcess = Process.GetCurrentProcess();
                return (CurrentProcess.WorkingSet64 / 1024 / 1024).ToString();
            }
            catch (Exception)
            {
                return "运存获取失败!";
            }
        }

        public static long GetHardDiskSpace(string str_HardDiskName)
        {

            long totalSize = new long();

            str_HardDiskName = str_HardDiskName + ":\\";

            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (System.IO.DriveInfo drive in drives)
            {

                if (drive.Name == str_HardDiskName)
                {

                    totalSize = drive.TotalSize / (1024 * 1024 * 1024);

                }

            }

            return totalSize;

        }

        /// <summary>  

        /// 获取指定驱动器的剩余空间总大小(单位为GB)  

        /// </summary>  

        /// <param name=”str_HardDiskName”>只需输入代表驱动器的字母即可 </param>  

        /// <returns> </returns>  

        public static long GetHardDiskFreeSpace(string str_HardDiskName)
        {

            long freeSpace = new long();

            str_HardDiskName = str_HardDiskName + ":\\";

            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (System.IO.DriveInfo drive in drives)
            {

                if (drive.Name == str_HardDiskName)
                {

                    freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024);

                }

            }

            return freeSpace;

        } 

        /// <summary>
        /// 保存日志运行记录
        /// </summary>
        public static void SaveLog(string Path, string LogMessage)
        {
            try
            {
                string LogPath = Path + "//" + System.DateTime.Now.ToString("yyyyMMdd") + ".txt";
                CreateFile(Path);
                System.IO.File.AppendAllText(LogPath, "\r\n" + LogMessage);
            }
            catch (Exception ex)
            {
                SaveErrorLog(外设.SysPras.Logpath, "SaveLog::" + ex.ToString());
            }
        }

        /// <summary>
        /// 保存异常日志
        /// </summary>
        /// <param name="path：路径"></param>
        /// <param name="ErrorMessage：错误信息"></param>
        public static void SaveErrorLog(string path, string ErrorMessage)
        {
            try
            {
                string LogPath = path + "//" + System.DateTime.Now.ToString("yyyyMMdd") + "ErrorLog.txt";
                CreateFile(path);
                string SaveErrorData = DateTime.Now.ToString("HH:mm:ss") + ">>>" + ErrorMessage;
                System.IO.File.AppendAllText(LogPath, "\r\n" + SaveErrorData);
            }
            catch (Exception)
            {

            }
            
        }

        /// <summary>
        /// 固定间隔删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Interval"></param>
        public static void DeleateFile(string FilePath, int Interval)
        {
            try
            {
                DirectoryInfo rootDirInfo = new DirectoryInfo(FilePath);
                if (!rootDirInfo.Exists) { return; }
                DateTime NowTime = DateTime.Now;
                FileSystemInfo[] dirs = rootDirInfo.GetFileSystemInfos();

                foreach (var item in dirs)
                {
                    DateTime CreateFileTime = item.CreationTime;
                    TimeSpan OutTime = NowTime - CreateFileTime;
                    if (OutTime.Days > Interval)
                    {
                        FileAttributes Attr = File.GetAttributes(item.FullName);
                        if (Attr == FileAttributes.Directory) { Directory.Delete(item.FullName, true); }
                        else { item.Delete(); }
                    }
                }
            }
            catch (Exception ex)
            {
                SaveErrorLog(外设.SysPras.Logpath, "DeleateFile::" + ex.ToString());
            }
        }

        //检索halcon函数


        public static void SaveAsCSV(string FilePath, string mes)
        {
            //先判断路径是否有，没有追加
            string CSVPath = FilePath + "//" + System.DateTime.Now.ToString("yyyyMMdd") + ".csv";
            CreateFile(FilePath);
            //添加内容就可以了,如果出现问题
            System.IO.StreamWriter Record = new System.IO.StreamWriter(CSVPath, true, System.Text.Encoding.UTF8);
            Record.WriteLine(mes);
            Record.Flush();
            Record.Close();
            Record.Dispose();
        }
    }
}


